/**
 * 1. 执行器函数是一个同步回调
 * 2. resolve 与 reject 函数的作用
 * 3. 改变状态的方法
 * 4. 状态只能改变一次
 */
//构造函数
function Promise(executor) {
  //声明实例对象的属性
  this.PromiseState = 'pending';
  this.PromiseResult = undefined;
  this.callbacks = [];

  //声明函数
  let resolve = value => {
    //判断
    if (this.PromiseState !== 'pending') return;
    //修改状态
    this.PromiseState = 'fulfilled';
    //设置结果值
    this.PromiseResult = value;
    //执行对应状态的回调函数
    this.callbacks.forEach(item => {
      item.success(this.PromiseResult);
    })
  }

  let reject = reason => {
    //判断
    if (this.PromiseState !== 'pending') return;
    //修改状态
    this.PromiseState = 'rejected';
    //设置结果值
    this.PromiseResult = reason;
    //执行对应状态的回调函数
    this.callbacks.forEach(item => {
      item.fail(this.PromiseResult);
    })
  }

  try {
    //调用执行器函数
    executor(resolve, reject);
  } catch (e) {
    reject(e);
  }
}

//then方法
Promise.prototype.then = function (onFulfilled, onRejected) {
  //判断两个参数
  if(typeof onFulfilled !== 'function'){
    onFulfilled = v => v;
  }
  if(typeof onRejected !== 'function'){
    onRejected = r => {throw r};
  }
  return new Promise((resolve, reject) => {
    let callback = (type) => {
      try {
        //获取回调函数的返回值
        let data = type(this.PromiseResult);
        //判断
        if (data instanceof Promise) {
          data.then(resolve, reject);
        } else {
          //如果不是 promise 数据
          resolve(data);
        }
      } catch (e) {
        reject(e);
      }
    }
    //判断成功
    if (this.PromiseState === 'fulfilled') {
      callback(onFulfilled);
    }
    //判断失败
    if (this.PromiseState === 'rejected') {
      callback(onRejected)
    }
    //判断 pending
    if (this.PromiseState === 'pending') {
      //保存回调函数
      this.callbacks.push({
        success: function(){
          callback(onFulfilled);
        },
        fail: function(){
          callback(onRejected);
        }
      })
    }
  })

}

//catch 方法
Promise.prototype.catch = function(onRejected){
  return this.then(undefined, onRejected);
}